﻿using Microsoft.SemanticKernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntermediateDemo;

internal class TrustedPrompt
{
    public static async Task TrustedTemplateAsync(Kernel kernel)
    {
        var trustedMessageFunction = KernelFunctionFactory.CreateFromMethod(
          () => "<message role=\"system\">你是一个很有帮助的助手，对中国的城市了如指掌</message>",
          "TrustedMessageFunction");
        var trustedContentFunction = KernelFunctionFactory.CreateFromMethod(() => "<text>北京是什么?</text>", "TrustedContentFunction");

        kernel.ImportPluginFromFunctions("TrustedPlugin", [trustedMessageFunction, trustedContentFunction]);

        var chatPrompt = """
                     {{TrustedPlugin.TrustedMessageFunction}}
                     <message role="user">{{$input}}</message>
                     <message role="user">{{TrustedPlugin.TrustedContentFunction}}</message>
                     """;
        var promptConfig = new PromptTemplateConfig(chatPrompt);
        var kernelArguments = new KernelArguments()
        {
            ["input"] = "<text>深圳是什么?</text>",
        };

#pragma warning disable SKEXP0001 // 类型仅用于评估，在将来的更新中可能会被更改或删除。取消此诊断以继续。
        var factory = new KernelPromptTemplateFactory() { AllowDangerouslySetContent = true };
#pragma warning restore SKEXP0001 // 类型仅用于评估，在将来的更新中可能会被更改或删除。取消此诊断以继续。
        var function = KernelFunctionFactory.CreateFromPrompt(promptConfig, factory);
        Console.WriteLine(await RenderPromptAsync(kernel, promptConfig, kernelArguments, factory));
        Console.WriteLine((await kernel.InvokeAsync(function, kernelArguments)).GetValue<string>());
    }

    static readonly IPromptTemplateFactory _promptTemplateFactory = new KernelPromptTemplateFactory();

    static Task<string> RenderPromptAsync(Kernel kernel, PromptTemplateConfig promptConfig, KernelArguments arguments,
    IPromptTemplateFactory? promptTemplateFactory = null)
    {
        promptTemplateFactory ??= _promptTemplateFactory;
        var promptTemplate = promptTemplateFactory.Create(promptConfig);
        return promptTemplate.RenderAsync(kernel, arguments);
    }
}
